angular.module('starter.controllers', ['ionic'])

//首页
  .controller('DashCtrl', function ($scope) {
    $scope.local = "长春大学";
    // var map, geolocation;
    // //加载地图，调用浏览器定位服务
    // map = new AMap.Map('container', {
    //     resizeEnable: true
    // });
    // map.plugin('AMap.Geolocation', function () {
    //     geolocation = new AMap.Geolocation({
    //         enableHighAccuracy: true,//是否使用高精度定位，默认:true
    //         timeout: 10000,          //超过10秒后停止定位，默认：无穷大
    //         buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
    //         zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    //         buttonPosition: 'RB'
    //     });
    //     map.addControl(geolocation);
    //     geolocation.getCurrentPosition();
    //     AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
    //     AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    // });
    // //解析定位结果
    // function onComplete(data) {
    //     var str = [];
    //     str.push(data.position.getLng());
    //     str.push(data.position.getLat());
    //     $scope.local = str;
    //
    // }
    //
    // //解析定位错误信息
    // function onError(data) {
    //     $scope.local = "定位失败";
    // }
    //
    $scope.doRefresh = function () {
      setTimeout(function () {
        $scope.$broadcast('scroll.refreshComplete');
      }, 2000);
    }
  })

  .controller('DashDetailCtrl', function ($scope) {
  })

  //订单列表界面
  .controller('OrderListCtrl', function ($scope, Orders) {
    Orders.getOrders(1)
      .then(function (orders) {
        $scope.orders = orders;
      }, function (error) {

        $scope.orders = null;
      });
    $scope.doRefresh = function () {
      Orders.getOrders(1)
        .then(function (orders) {
          $scope.orders = orders;
        }, function (error) {
          $scope.orders = null;
        })
        .then(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
    }
  })

  //订单详情界面
  .controller('OrderListDetailCtrl', function ($scope, $stateParams, Orders, Shops) {
    $scope.ordername = Orders.get($stateParams.orderId).name;
    Orders.getOrder($stateParams.orderId)
      .then(function (order) {
        if (order === "" || order === undefined || order === null){
          alert(order);
        }
        $scope.order = order;
      }, function (error) {
        alert(error);
      });

    $scope.doRefresh = function () {
      Orders.getOrder($stateParams.orderId)
        .then(function (order) {
          $scope.order = order;
        }, function (error) {
          alert(error);
        })
        .then(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
    }
  })

  //商铺列表
  .controller('ShopListCtrl', function ($scope, $state, $rootScope, $http, Shops) {
    if ($rootScope.shops != undefined) {
      $scope.shops = $rootScope.shops;
      //$ionicLoading.hide();
    } else {
      Shops.all(1).then(
          function (response) {
            $rootScope.shops = response;
            $scope.shops = response;
          },
          function (error) {
            alert("连接服务器失败");
          }
        );
    }
    $scope.doRefresh = function () {
      Shops.all(1)
        .then(
          function (response) {
            $rootScope.shops = response;
            $scope.shops = $rootScope.shops;
          },
          function (error) {
            alert("连接服务器失败");
          }
        )
        .then(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
    }
  })

  //商铺详情
  .controller('ShopDetailCtrl', function ($scope, $state, $stateParams, $rootScope, Shops, Foods, Orders) {
    $scope.totalprice = 0;
    Orders.initOrder($stateParams.shopId);
    $scope.shop = Shops.get($stateParams.shopId);
    Foods.getFoods($stateParams.shopId)
      .then(function (foods) {
        $scope.foods = foods;
      });
    $scope.add = function (shop, food) {
      if (food.count < food.isempty) {
        food.count = food.count + 1;
        $scope.totalprice = Orders.add(shop, food).totalPrice;
      }
    };
    $scope.sub = function (shop, food) {
      if (food.count > 0) {
        food.count = food.count - 1;
        $scope.totalprice = Orders.sub(shop, food).totalPrice;
      }
    };
    $scope.pay = function () {
      if ($scope.totalprice > 0) {
        $state.go('shop-order');
      }
    }
  })

  //订单信息
  .controller('ShopOrderCtrl', function ($scope, $state, $stateParams, $ionicHistory, Shops, Foods, Orders, Addresses) {
    var order = Orders.getTempOrder();
    if (order == undefined || order == null) {
      $state.go('error');
    }else{
      console.info("shopId:" + order.shopId +"\norder:" + JSON.stringify(order) +"\nfoodsId:"+JSON.stringify(order.foods)+"\nfoods:" + JSON.stringify(Foods.getOrdersFood(order.foods)));
      var shop = Shops.get(order.shopId);
      $scope.shop = shop;
      $scope.totalPrice = order.totalPrice + (shop.peisong==undefined?0:shop.peisong);
      $scope.foods = Foods.getOrdersFood(order.foods);
      $scope.address = Addresses.getSelectedAddress();
      $ionicHistory.clearCache();
      $scope.pay = function(shop){
      };
    }
  })

  //地址列表
  .controller('AddressListCtrl', function ($scope, $state, $stateParams, Addresses) {
    function show(id){
      Addresses.getAddresses(id)
        .then(
          function(addressList){
            $scope.addresses = addressList;
          },
          function(error){
            alert("获取失败，请刷新重试！");
          }
        );
    }
    show(1);

    $scope.doRefresh = function(){
      Addresses.getAddresses(1)
        .then(
          function(addressList){
            $scope.addresses = addressList;
          },
          function(error){
            alert("获取失败，请刷新重试！");
          }
        )
        .then(function () {
          $scope.$broadcast('scroll.refreshComplete');
        });
    }

    $scope.delete = function(deliveryaddressid){
      Addresses.delAddress(deliveryaddressid)
        .then(
          function(result){

          },
          function(error){
            alert("获取失败，请刷新重试！");
          }
        )
        .then(function() {
          show(1);
        });
    }
  })

  //地址编辑界面
  .controller('AddressEditCtrl', function ($scope, $state, $stateParams, $ionicHistory, Addresses) {
    // alert($stateParams.addressId);
    if ($stateParams.addressId == "new") {
      $scope.title = "新增地址";
      var address = {};
      address.sex = 'male';
      $scope.address = address;
    } else {
      $scope.title = "修改地址";
      Addresses.getAddress($stateParams.addressId)
        .then(
          function(address){
            address.sex = 'male';
            $scope.address = address;
          },
          function(error){
            alert("获取失败，请重试！");
            $ionicHistory.goBack();
          }
        );
    }
    $scope.ok = function(address){
      if (address.name == undefined || address.sex == undefined || address.phonenub == undefined || address.address == undefined ||
      address.name == "" || address.sex == "" || address.phonenub == "" || address.address == "" || !validatemobile(address.phonenub)) {
        alert("请完整添加数据");
      }else{
        if ($stateParams.addressId == "new") {
          address.isselect = 1;
          address.userid = 1;
          Addresses.saveAddress(address).then(
            function(result){
              alert(result);
              $ionicHistory.goBack();
            },
            function(error){
              alert("保存失败，请重试！");
            }
          );
        } else {
          Addresses.updeteAddress(address).then(
            function(result){
              $ionicHistory.goBack();
            },
            function(error){
              alert("保存失败，请重试！");
            }
          );
        }
      }
    };
    function validatemobile(mobile)
    {
        if(mobile.length==0) {
           alert('请输入手机号码！');
           return false;
        }
        if(mobile.length!=11) {
            alert('请输入有效的手机号码！');
            return false;
        }
        var myreg = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/;
        if(!myreg.test(mobile)) {
            alert('请输入有效的手机号码！');
            return false;
        }
        return true;
      }
  })

  //我的界面
  .controller('AccountCtrl', function ($scope, $state, Users) {
    $scope.user = Users.getRandom();
  })

  //登录界面
  .controller('AccountLoginCtrl', function ($scope, $state, $rootScope) {
    $scope.signIn = function (user) {
      $rootScope.isLogin = true;
      if ($rootScope.toState != undefined)
        $state.go($rootScope.toState, {}, {toParams: $rootScope.toParams});
      else
        $state.go("tab.account", {}, {reload: true});
    }
  })

  //完成订单列表
  .controller('CompletedOrderListCtrl', function ($scope) {

  })

  //完成订单详情
  .controller('CompletedOrderDetailCtrl', function ($scope) {

  })

  //信息详情界面
  .controller('AccountDetailCtrl', function ($scope, $stateParams, Users) {
    $scope.user = Users.get($stateParams.userId);
  })

  .controller('HouseCtrl', function ($scope, $ionicSlideBoxDelegate) {
    //为了验证属性active-slide定义的模型，angularjs是mvc模式
    $scope.model = {
      activeIndex: 0
    };

    //此事件对应的是pager-click属性，当显示图片是有对应数量的小圆点，这是小圆点的点击事件
    $scope.pageClick = function (index) {
      //alert(index);
      $scope.model.activeIndex = 2;
    };

    //当图片切换后，触发此事件，注意参数
    $scope.slideHasChanged = function ($index) {
      //alert($index);
    };
    //这是属性delegate-handle的验证使用的，其实没必要重定义，直接使用$ionicSlideBoxDelegate就可以
    $scope.delegateHandle = $ionicSlideBoxDelegate;
  });
